import { Editor } from 'tinymce'
import { nextTick, onBeforeUnmount } from 'vue'

import { initInlineTinymce } from '@/utils'

type HtmlElId = string

interface TinymceHookOptions {
  defaultFontFamily?: string
  inline?: boolean
  // 工具栏容器
  fixed_toolbar_container?: string
}

export function useTinymce(options?: TinymceHookOptions) {
  const {
    fixed_toolbar_container,
    inline = true,
    defaultFontFamily = '方正仿宋_GBK'
  } = options || {}
  const tinymceEditorInstanceMap = new Map<string, Editor>()

  // 初始化实例
  function initEditorInstance(id: HtmlElId) {
    if (tinymceEditorInstanceMap.has(id)) {
      return
    }

    nextTick(() => {
      initInlineTinymce({
        inline,
        fixed_toolbar_container,
        selector: `#${id}`,
        setup: (editor) => {
          tinymceEditorInstanceMap.set(id, editor)

          nextTick(() => {
            if (inline) {
              editor?.getBody()?.blur()
            }

            if (editor.getBody) {
              editor.getBody().style.fontFamily = defaultFontFamily
            }
          })
        }
      })
    })
  }

  // 销毁实例
  function destroyInstance(id: HtmlElId) {
    if (id && tinymceEditorInstanceMap.has(id)) {
      tinymceEditorInstanceMap.get(id)?.destroy()
      tinymceEditorInstanceMap.delete(id)
    }
  }

  function destroyAllInstance() {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for (const [key, value] of tinymceEditorInstanceMap.entries()) {
      value.destroy()
    }
    tinymceEditorInstanceMap.clear()
  }

  onBeforeUnmount(() => {
    destroyAllInstance()
  })

  return {
    tinymceEditorInstanceMap,
    initEditorInstance,
    destroyInstance,
    destroyAllInstance
  }
}
